<template>
  <div class="app-container">
    <div class="search-bar">
      <el-card shadow="never" style="margin-bottom: 10px">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true">
          <el-form-item label="主键" prop="id">
            <el-input
              v-model="queryParams.id"
              placeholder="主键"
              clearable
              @keyup.enter="handleQuery()"
            />
          </el-form-item>
          <el-form-item label="报告日期" prop="reportDate">
            <el-date-picker
              class="!w-[240px]"
              v-model="queryParams.reportDate"
              type="daterange"
              range-separator="~"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item label="创建时间" prop="createTime">
            <el-date-picker
              v-model="queryParams.createTime"
              type="daterange"
              range-separator="~"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="更新时间" prop="updateTime">
            <el-date-picker
              v-model="queryParams.updateTime"
              type="daterange"
              range-separator="~"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">
              <template #icon><Search /></template>
              搜索
            </el-button>
            <el-button @click="handleResetQuery">
              <template #icon><Refresh /></template>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button
          v-hasPerm="['system:daily-sales-report:add']"
          type="success"
          @click="handleOpenDialog()"
        >
          <template #icon><Plus /></template>
          新增
        </el-button>
        <el-button
          v-hasPerm="['system:daily-sales-report:delete']"
          type="danger"
          :disabled="removeIds.length === 0"
          @click="handleDelete()"
        >
          <template #icon><Delete /></template>
          删除
        </el-button>
        <el-button type="warning"
          @click="handleImportExcel"
          :loading="importLoading"
        >
          <template #icon><Upload /></template>
          文件上传
        </el-button>
        <el-button type="primary"
          @click="handleExportExcel"
          :loading="exportLoading"
        >
          <template #icon><Download /></template>
          日报下载
        </el-button>
      </div>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="pageData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          key="id"
          label="主键"
          prop="id"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="reportDate"
          label="报告日期"
          prop="reportDate"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="averageTransactionValue"
          label="客单价"
          prop="averageTransactionValue"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="conversionRate"
          label="转化率"
          prop="conversionRate"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="monthlySalesTarget"
          label="月度销售任务（元）"
          prop="monthlySalesTarget"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="currentSalesAmount"
          label="目前已完成销售额（元）"
          prop="currentSalesAmount"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="salesProgress"
          label="销售进度（%）"
          prop="salesProgress"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="timeProgress"
          label="时间进度（%）"
          prop="timeProgress"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="gmvYoyChange"
          label="GMV同比变化（%）"
          prop="gmvYoyChange"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="avgConversionRate"
          label="本月平均转化率"
          prop="avgConversionRate"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="avgTransactionValue"
          label="本月平均客单价"
          prop="avgTransactionValue"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="totalSalesQuantity"
          label="本月总销售数量（件）"
          prop="totalSalesQuantity"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="createTime"
          label="创建时间"
          prop="createTime"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="updateTime"
          label="更新时间"
          prop="updateTime"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="isDeleted"
          label="删除标记(0:正常 1:删除)"
          prop="isDeleted"
          min-width="150"
          align="center"
        />
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button
              v-hasPerm="['system:daily-sales-report:edit']"
              type="primary"
              size="small"
              link
              @click="handleOpenDialog(scope.row.id)"
            >
              <template #icon><Edit /></template>
              编辑
            </el-button>
            <el-button
              v-hasPerm="['system:daily-sales-report:delete']"
              type="danger"
              size="small"
              link
              @click="handleDelete(scope.row.id)"
            >
              <template #icon><Delete /></template>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery()"
      />
    </el-card>

    <!-- TP运营日报表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="500px"
      @close="handleCloseDialog"
    >
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="主键" prop="id">
          <el-input
            v-model="formData.id"
            placeholder="主键"
          />
        </el-form-item>

        <el-form-item label="报告日期" prop="reportDate">
          <el-date-picker
            class="!w-[240px]"
            v-model="formData.reportDate"
            type="date"
            placeholder="报告日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <el-form-item label="客单价" prop="averageTransactionValue">
          <el-input
            v-model="formData.averageTransactionValue"
            placeholder="客单价"
          />
        </el-form-item>

        <el-form-item label="转化率" prop="conversionRate">
          <el-input
            v-model="formData.conversionRate"
            placeholder="转化率"
          />
        </el-form-item>

        <el-form-item label="月度销售任务（元）" prop="monthlySalesTarget">
          <el-input
            v-model="formData.monthlySalesTarget"
            placeholder="月度销售任务（元）"
          />
        </el-form-item>

        <el-form-item label="目前已完成销售额（元）" prop="currentSalesAmount">
          <el-input
            v-model="formData.currentSalesAmount"
            placeholder="目前已完成销售额（元）"
          />
        </el-form-item>

        <el-form-item label="销售进度（%）" prop="salesProgress">
          <el-input
            v-model="formData.salesProgress"
            placeholder="销售进度（%）"
          />
        </el-form-item>

        <el-form-item label="时间进度（%）" prop="timeProgress">
          <el-input
            v-model="formData.timeProgress"
            placeholder="时间进度（%）"
          />
        </el-form-item>

        <el-form-item label="GMV同比变化（%）" prop="gmvYoyChange">
          <el-input
            v-model="formData.gmvYoyChange"
            placeholder="GMV同比变化（%）"
          />
        </el-form-item>

        <el-form-item label="本月平均转化率" prop="avgConversionRate">
          <el-input
            v-model="formData.avgConversionRate"
            placeholder="本月平均转化率"
          />
        </el-form-item>

        <el-form-item label="本月平均客单价" prop="avgTransactionValue">
          <el-input
            v-model="formData.avgTransactionValue"
            placeholder="本月平均客单价"
          />
        </el-form-item>

        <el-form-item label="本月总销售数量（件）" prop="totalSalesQuantity">
          <el-input
            v-model="formData.totalSalesQuantity"
            placeholder="本月总销售数量（件）"
          />
        </el-form-item>

        <el-form-item label="创建时间" prop="createTime">
          <el-date-picker
            v-model="formData.createTime"
            type="datetime"
            placeholder="创建时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>

        <el-form-item label="更新时间" prop="updateTime">
          <el-date-picker
            v-model="formData.updateTime"
            type="datetime"
            placeholder="更新时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>

        <el-form-item label="删除标记(0:正常 1:删除)" prop="isDeleted">
          <el-input
            v-model="formData.isDeleted"
            placeholder="删除标记(0:正常 1:删除)"
          />
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit()">确定</el-button>
          <el-button @click="handleCloseDialog()">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog
      v-model="importDialogVisible"
      :title="dialog.title"
      width="800px"
    >
      <el-upload
        ref="uploadRef"
        :auto-upload="false"
        :limit="5"
        :on-exceed="handleExceed"
        :on-change="handleFileChange"
        :on-remove="handleFileRemove"
        :show-file-list="true"
        accept=".xlsx"
        multiple
        drag
      >
        <el-icon class="el-icon--upload"><Upload /></el-icon>
        <div class="el-upload__text">拖拽文件到此处，或 <em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>支持批量上传，最多5个.xlsx格式文件</span>
            <el-button type="primary" link @click="handleDownloadTemplate">下载模板</el-button>
          </div>
        </template>
      </el-upload>
      <div v-if="importResult" class="mt-15">
        <el-alert
          :title="`导入结果: 成功${importResult.validCount}条，失败${importResult.invalidCount}条，总计${importResult.validCount + importResult.invalidCount}条`"
          :type="importResult.invalidCount > 0 ? 'warning' : 'success'"
          show-icon
        />
        <el-collapse v-if="importResult.errorMsgs && importResult.errorMsgs.length > 0" class="mt-10px">
          <el-collapse-item title="错误详情">
            <ul class="error-list">
              <li v-for="(msg, index) in importResult.errorMsgs" :key="index" class="text-red-500">
                {{ msg }}
              </li>
            </ul>
          </el-collapse-item>
        </el-collapse>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="importDialogVisible = false">取 消</el-button>
          <el-button type="primary" :loading="uploadLoading" @click="submitImport">
            批量导入
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "DailySalesReport",
  inheritAttrs: false,
});

import DailySalesReportAPI, { DailySalesReportPageVO, DailySalesReportForm, DailySalesReportPageQuery } from "@/api/system/daily-sales-report";
import { downloadExcel } from "@/utils/download";
import { Plus, Delete, Search, Refresh, Download, Upload, Edit } from '@element-plus/icons-vue';

const queryFormRef = ref();
const dataFormRef = ref();

const loading = ref(false);
const exportLoading = ref(false);
const importLoading = ref(false);
const templateLoading = ref(false);
const uploadLoading = ref(false);
const removeIds = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<DailySalesReportPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

// TP运营日报表格数据
const pageData = ref<DailySalesReportPageVO[]>([]);

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

// TP运营日报表单数据
const formData = reactive<DailySalesReportForm>({});

// TP运营日报表单校验规则
const rules = reactive({
  id: [{ required: true, message: "请输入主键", trigger: "blur" }],
  reportDate: [{ required: true, message: "请输入报告日期", trigger: "blur" }],
  averageTransactionValue: [{ required: true, message: "请输入客单价", trigger: "blur" }],
  conversionRate: [{ required: true, message: "请输入转化率", trigger: "blur" }],
  monthlySalesTarget: [{ required: true, message: "请输入月度销售任务（元）", trigger: "blur" }],
  currentSalesAmount: [{ required: true, message: "请输入目前已完成销售额（元）", trigger: "blur" }],
  salesProgress: [{ required: true, message: "请输入销售进度（%）", trigger: "blur" }],
  timeProgress: [{ required: true, message: "请输入时间进度（%）", trigger: "blur" }],
  gmvYoyChange: [{ required: true, message: "请输入GMV同比变化（%）", trigger: "blur" }],
  avgConversionRate: [{ required: true, message: "请输入本月平均转化率", trigger: "blur" }],
  avgTransactionValue: [{ required: true, message: "请输入本月平均客单价", trigger: "blur" }],
  totalSalesQuantity: [{ required: true, message: "请输入本月总销售数量（件）", trigger: "blur" }],
  createTime: [{ required: true, message: "请输入创建时间", trigger: "blur" }],
  updateTime: [{ required: true, message: "请输入更新时间", trigger: "blur" }],
  isDeleted: [{ required: true, message: "请输入删除标记(0:正常 1:删除)", trigger: "blur" }],
});

// 添加导入对话框相关变量
const importDialogVisible = ref(false);
const importFiles = ref<File[]>([]);
const importResult = ref<any>(null);
const uploadRef = ref();

/** 查询TP运营日报 */
function handleQuery() {
  loading.value = true;
  DailySalesReportAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置TP运营日报查询 */
function handleResetQuery() {
  queryFormRef.value!.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/** 打开TP运营日报弹窗 */
function handleOpenDialog(id?: number) {
  dialog.visible = true;
  if (id) {
    dialog.title = "修改TP运营日报";
    DailySalesReportAPI.getFormData(id).then((data) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增TP运营日报";
  }
}

/** 提交TP运营日报表单 */
function handleSubmit() {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const id = formData.id;
      if (id) {
        DailySalesReportAPI.update(id, formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        DailySalesReportAPI.add(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭TP运营日报弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
  formData.id = undefined;
}

/** 删除TP运营日报 */
function handleDelete(id?: number) {
  const ids = [id || removeIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      DailySalesReportAPI.deleteByIds(ids)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

/** 导出Excel */
async function handleExportExcel() {
  try {
    exportLoading.value = true;
    ElMessage.info('正在导出，请稍候...');
    
    // 构建导出参数，将查询条件转换为后端期望的格式
    const exportParams: any = {};
    
    // 处理日期范围
    if (queryParams.reportDate && queryParams.reportDate.length >= 2) {
      exportParams.reportDate = queryParams.reportDate;
    }
    
    // 添加其他查询条件
    if (queryParams.id) {
      exportParams.id = queryParams.id;
    }
    
    const response = await DailySalesReportAPI.exportExcel(exportParams);
    
    // 创建blob对象
    const blob = new Blob([response.data as BlobPart], { 
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
    });
    
    // 创建下载链接
    const fileName = `日报数据_${new Date().getTime()}.xlsx`;
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = fileName;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(link.href);
    
    ElMessage.success('导出成功');
  } catch (error) {
    console.error('导出失败:', error);
    ElMessage.error('导出失败，请重试');
  } finally {
    exportLoading.value = false;
  }
}

/** 导入Excel */
function handleImportExcel() {
  importDialogVisible.value = true;
  importFiles.value = [];
  importResult.value = null;
  if (uploadRef.value) {
    uploadRef.value.clearFiles();
  }
}

/** 下载导入模板 */
async function handleDownloadTemplate() {
  try {
    templateLoading.value = true;
    ElMessage.info('正在下载模板，请稍候...');
    
    const response = await DailySalesReportAPI.downloadTemplate();
    
    // 创建blob对象
    const blob = new Blob([response.data as BlobPart], { 
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
    });
    
    // 创建下载链接
    const fileName = `日报数据导入模板.xlsx`;
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = fileName;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(link.href);
    
    ElMessage.success('模板下载成功');
  } catch (error) {
    console.error('模板下载失败:', error);
    ElMessage.error('模板下载失败，请重试');
  } finally {
    templateLoading.value = false;
  }
}

/** 文件超出限制回调 */
function handleExceed() {
  ElMessage.warning('最多只能上传5个文件');
}

/** 文件状态改变时的回调 */
function handleFileChange(file: any) {
  importFiles.value.push(file.raw);
}

/** 文件移除时的回调 */
function handleFileRemove(file: any) {
  const index = importFiles.value.findIndex((f: File) =>
    f.name === file.name && f.size === file.size
  );
  if (index !== -1) {
    importFiles.value.splice(index, 1);
  }
}

/** 提交导入 */
async function submitImport() {
  if (importFiles.value.length === 0) {
    ElMessage.warning('请先选择要上传的Excel文件');
    return;
  }

  uploadLoading.value = true;

  try {
    let totalValidCount = 0;
    let totalInvalidCount = 0;
    let allMessages: string[] = [];

    // 依次处理每个文件
    for (const file of importFiles.value) {
      const result = await DailySalesReportAPI.importExcel(file);
      totalValidCount += result.validCount;
      totalInvalidCount += result.invalidCount;
      if (result.errorMsgs) {
        allMessages = allMessages.concat(result.errorMsgs.map((msg: string) => `[${file.name}] ${msg}`));
      }
    }

    // 更新导入结果
    importResult.value = {
      validCount: totalValidCount,
      invalidCount: totalInvalidCount,
      errorMsgs: allMessages,
      success: totalInvalidCount === 0
    };

    if (totalInvalidCount === 0) {
      ElMessage.success(`批量导入成功，共导入${totalValidCount}条数据`);
      // 导入成功后关闭对话框
      setTimeout(() => {
        importDialogVisible.value = false;
      }, 2000);
    } else {
      ElMessage.warning(`导入完成，成功${totalValidCount}条，失败${totalInvalidCount}条`);
    }

    // 刷新表格数据
    handleQuery();
  } catch (error) {
    console.error('导入出错:', error);
    ElMessage.error('导入失败，请检查文件格式是否正确');
  } finally {
    uploadLoading.value = false;
  }
}

onMounted(() => {
  handleQuery();
});
</script>

<style lang="scss" scoped>
.error-list {
  margin: 0;
  padding-left: 20px;
}

.mt-15 {
  margin-top: 15px;
}

.mt-10px {
  margin-top: 10px;
}

.text-red-500 {
  color: #ef4444;
}

.text-center {
  text-align: center;
}
</style>
